<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>文件上传</title>
  <style>
    #dropzone {
      width: 300px;
      height: 200px;
      border: 2px dashed #bbb;
      border-radius: 5px;
      text-align: center;
      line-height: 200px;
      font-family: Arial, sans-serif;
      color: #bbb;
      margin: 50px auto;
      cursor: pointer;
    }
    #dropzone.hover {
      border-color: #333;
      color: #333;
    }
    #fileInput {
      display: none;
    }
    #messages {
      width: 300px;
      margin: 20px auto;
      font-family: Arial, sans-serif;
      text-align: left;
    }
    .success {
      color: green;
    }
    .error {
      color: red;
    }
  </style>
</head>
<body>
  <div id="dropzone">拖拽文件到此处或点击上传</div>
  <input type="file" id="fileInput" multiple>
  <div id="messages"></div>

  <script>
    const dropzone = document.getElementById('dropzone');
    const fileInput = document.getElementById('fileInput');
    const messages = document.getElementById('messages');
    let messageCounter = 0;

    dropzone.addEventListener('dragover', function(e) {
      e.preventDefault();
      dropzone.classList.add('hover');
    });

    dropzone.addEventListener('dragleave', function(e) {
      e.preventDefault();
      dropzone.classList.remove('hover');
    });

    dropzone.addEventListener('drop', function(e) {
      e.preventDefault();
      dropzone.classList.remove('hover');
      const files = e.dataTransfer.files;
      uploadFiles(files);
    });

    dropzone.addEventListener('click', function() {
      fileInput.click();
    });

    fileInput.addEventListener('change', function() {
      const files = fileInput.files;
      uploadFiles(files);
      fileInput.value = '';
    });

    function uploadFiles(files) {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const formData = new FormData();
        formData.append('file', file);

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/upload', true);

        xhr.onload = function () {
          messageCounter++;
          if (xhr.status === 200) {
            const successMsg = document.createElement('div');
            successMsg.textContent = `${messageCounter}．文件「${file.name}」上传成功。`;
            successMsg.className = 'success';
            messages.appendChild(successMsg);
          } else {
            const errorMsg = document.createElement('div');
            errorMsg.textContent = `${messageCounter}．上传「${file.name}」时发生错误。`;
            errorMsg.className = 'error';
            messages.appendChild(errorMsg);
          }
        };

        xhr.onerror = function () {
          messageCounter++;
          const errorMsg = document.createElement('div');
          errorMsg.textContent = `${messageCounter}．上传「${file.name}」时发生错误。`;
          errorMsg.className = 'error';
          messages.appendChild(errorMsg);
        };

        xhr.send(formData);
      }
    }
  </script>
</body>
</html>
